package com.zlll.winner.service.media;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlll.winner.business.model.media.MediaMenu;
import com.zlll.winner.business.model.media.MediaNewList;
import com.zlll.winner.business.model.sysUser.SysUser;
import com.zlll.winner.business.vo.media.MediaNewListVo;
import com.zlll.winner.enums.CommonEnum;
import com.zlll.winner.enums.media.MediaEnum;
import com.zlll.winner.mapper.media.MediaMenuMapper;
import com.zlll.winner.mapper.media.MediaNewListMapper;
import com.zlll.winner.business.service.media.IMediaNewListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlll.winner.service.media.async.MediaNewListAsyncService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;


import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 电台节目列表 服务实现类
 * </p>
 *
 * @author Walert
 * @since 2019-10-04
 */
@Service
public class MediaNewListServiceImpl extends ServiceImpl<MediaNewListMapper, MediaNewList> implements IMediaNewListService {

    @Autowired
    private MediaNewListAsyncService mediaNewListAsyncService;

    @Resource
    private MediaMenuMapper mediaMenuMapper;

    /**
     * 条件查找记录
     * @param params
     * @return
     */
    @Override
    public IPage<MediaNewList> fetchNewList(JSONObject params){
        QueryWrapper<MediaNewList> queryWrapper = new QueryWrapper<>();
        Integer pageNo = params.getInteger("pageNo");
        Integer pageSize = params.getInteger("pageSize");
        IPage<MediaNewList> page = new Page<>(pageNo, pageSize);

        Integer status = params.getInteger("status");
        if(status != null){
            queryWrapper.eq("status",status);
            if(status.equals(MediaEnum.StatusEnum.REPLAY.val())){
                queryWrapper.orderByDesc("show_end_time");
            }else if(status.equals(MediaEnum.StatusEnum.WAIT.val())){
                queryWrapper.gt("show_begin_time",System.currentTimeMillis());
                queryWrapper.orderByAsc("show_begin_time");
            }
        }else{
            queryWrapper.orderByDesc("create_time");
        }
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 分页查找节目列表
     *
     * @param params
     * @return
     */
    @Override
    public Object fetchNewListPage(JSONObject params) {
        Integer pageNo = params.getInteger("pageNo");
        Integer pageSize = params.getInteger("pageSize");
        IPage<MediaNewListVo> page = new Page<>(pageNo, pageSize);
        QueryWrapper<MediaNewListVo> queryWrapper = new QueryWrapper<>();
        Long showDate = params.getLong("showDate");
        if (showDate == null) {
            showDate = DateUtil.parse(DateUtil.today()).getTime();
        }
        String menuName = params.getString("menuName");
        if (StringUtils.isNotBlank(menuName)) {
            queryWrapper.like("t.name", menuName);
        }
        String topic = params.getString("topic");
        if (StringUtils.isNotBlank(topic)) {
            queryWrapper.like("m1.show_topic", topic);
        }
        queryWrapper.eq("t.is_del", CommonEnum.DelEnum.UNDEL.val());
        queryWrapper.eq("t.type", MediaEnum.TypeEnum.NEWLIST.val());
        return baseMapper.fetchNewListPage(page, queryWrapper, showDate);
    }


    /**
     * 分页查找节目列表
     *
     * @param params
     * @return
     */
    @Override
    public Object fetchNewListWeApp(JSONObject params) {
        QueryWrapper<MediaNewListVo> queryWrapper = new QueryWrapper<>();
        Long showDate = params.getLong("showDate");
        if (showDate == null) {
            showDate = DateUtil.parse(DateUtil.today()).getTime();
        }
        queryWrapper.eq("t.is_del", CommonEnum.DelEnum.UNDEL.val());
        queryWrapper.eq("t.type", MediaEnum.TypeEnum.NEWLIST.val());
        return baseMapper.fetchNewListList(queryWrapper, showDate);
    }

    /**
     * 根据腾讯云录制任务ID获取记录
     * @param taskId
     * @return
     */
    @Override
    public MediaNewList getMediaNewListByTaskId(Long taskId){
        List<MediaNewList> mediaNewLists = baseMapper.selectList(Wrappers.<MediaNewList>lambdaQuery().eq(MediaNewList::getTaskId, taskId));
        if(mediaNewLists!=null && mediaNewLists.size() > 0){
            return mediaNewLists.get(0);
        }
        return null;
    }

    /**
     * 保存对象
     *
     * @param params
     * @return
     */
    @Override
    public Object saveNewList(JSONObject params, SysUser user) {
        MediaNewList mediaNewList = params.toJavaObject(MediaNewList.class);

        String menuBeginTime = params.getString("menuBeginTime");
        String menuEndTime = params.getString("menuEndTime");
        String showDateStr = params.getString("showDateStr");
        String beginDateTime = showDateStr.concat(" ").concat(menuBeginTime).concat(":00");
        String endDateTime;
        if ("00:00".equals(menuEndTime)) {
            DateTime dateTime = DateUtil.parse(showDateStr, DatePattern.NORM_DATE_PATTERN);
            Calendar calendar = dateTime.toCalendar();
            calendar.add(Calendar.DATE, 1);
            Date showDate = calendar.getTime();
            endDateTime = DateUtil.format(showDate, DatePattern.NORM_DATE_PATTERN).concat(" ").concat(menuEndTime).concat(":00");
        } else {
            endDateTime = showDateStr.concat(" ").concat(menuEndTime).concat(":00");
        }
        long beginTime = DateUtil.parse(beginDateTime, DatePattern.NORM_DATETIME_PATTERN).getTime();
        long endTime = DateUtil.parse(endDateTime, DatePattern.NORM_DATETIME_PATTERN).getTime();

        mediaNewList.setShowBeginTime(beginTime);
        mediaNewList.setShowEndTime(endTime);

        JSONObject hostOne = params.getJSONObject("hostOne");
        mediaNewList.setHostOneId(hostOne.getLong("id"));
        mediaNewList.setHostOneName(hostOne.getString("name"));

        JSONObject hostTwo = params.getJSONObject("hostTwo");
        if (hostTwo != null) {
            mediaNewList.setHostTwoId(hostOne.getLong("id"));
            mediaNewList.setHostTwoName(hostOne.getString("name"));
        }

        mediaNewList.setCreateTime(System.currentTimeMillis());
        mediaNewList.setCreateUser(user.getUserName());
        mediaNewList.setIsDel(CommonEnum.DelEnum.UNDEL.val());

        int insert = baseMapper.insert(mediaNewList);
        if (insert > 0) {
            mediaNewListAsyncService.createLiveRecord(mediaNewList.getId(), beginDateTime, endDateTime);
        }
        return mediaNewList;
    }

    /**
     * 删除视听节目列表内容
     * @param mediaNewListId
     * @param user
     * @return
     */
    @Override
    public Object deleteNewList(Long mediaNewListId ,SysUser user) {
        MediaNewList mediaNewList = baseMapper.selectById(mediaNewListId);
        if (mediaNewList != null) {
            mediaNewList.setUpdateTime(System.currentTimeMillis());
            mediaNewList.setUpdateUser(user.getUserName());
            mediaNewList.setIsDel(CommonEnum.DelEnum.DEL.val());
            int i = baseMapper.updateById(mediaNewList);
            if (i > 0) {
                mediaNewListAsyncService.deleteLiveRecord(mediaNewList.getTaskId());
            }
        }
        return mediaNewList;
    }

    /**
     * 获取当前直播的节目
     * @return
     */
    @Override
    public Object livingMediaNewList(){
        long currentTime = System.currentTimeMillis();
        MediaNewListVo mediaNewListByTime = baseMapper.getMediaNewListByTime(currentTime);
        if(mediaNewListByTime != null && mediaNewListByTime.getStatus().equals(MediaEnum.StatusEnum.WAIT.val())){
            mediaNewListByTime.setStatus(MediaEnum.StatusEnum.PLAY.val());
            mediaNewListByTime.setUpdateTime(System.currentTimeMillis());
            baseMapper.updateById(mediaNewListByTime);
        }else{
            if(mediaNewListByTime == null) {
                List<MediaMenu> mediaMenus = mediaMenuMapper.selectList(
                        Wrappers.<MediaMenu>lambdaQuery()
                                .eq(MediaMenu::getType, MediaEnum.TypeEnum.NEWLIST.val())
                                .eq(MediaMenu::getIsDel, CommonEnum.DelEnum.UNDEL.val())
                                .orderByAsc(MediaMenu::getId));
                if (mediaMenus != null && mediaMenus.size() > 0) {
                    String today = DateUtil.today();
                    long timeMillis = System.currentTimeMillis();
                    for (MediaMenu mediaMenu : mediaMenus) {
                        String endTimeStr = today.concat(" ").concat(mediaMenu.getEndTime()).concat(":00");
                        long endTime = DateUtil.parse(endTimeStr, DatePattern.NORM_DATETIME_PATTERN).getTime();
                        if ("00:00".equals(mediaMenu.getEndTime())) {
                            DateTime dateTime = DateUtil.parse(today, DatePattern.NORM_DATE_PATTERN);
                            Calendar calendar = dateTime.toCalendar();
                            calendar.add(Calendar.DATE, 1);
                            endTime = calendar.getTime().getTime();
                        }
                        if (endTime > timeMillis) {
                            String beginTimeStr = today.concat(" ").concat(mediaMenu.getBeginTime()).concat(":00");
                            long beginTime = DateUtil.parse(beginTimeStr, DatePattern.NORM_DATETIME_PATTERN).getTime();
                            mediaNewListByTime = new MediaNewListVo();
                            mediaNewListByTime.setMenuName(mediaMenu.getName());
                            mediaNewListByTime.setShowBeginTime(beginTime);
                            mediaNewListByTime.setShowEndTime(endTime);
                            mediaNewListByTime.setShowTitle(mediaMenu.getName());
                            mediaNewListByTime.setShowTopic(mediaMenu.getName());
                            mediaNewListByTime.setListenInNum(0);
                            break;
                        }
                    }
                }
            }
        }
        mediaNewListByTime.setListenOnLineNum(300+mediaNewListByTime.getListenInNum());
        return mediaNewListByTime;
    }


    /**
     * 复制昨天节目清单
     * @param params
     * @param user
     * @return
     */
    @Override
    public Object copyYesterdayShow(JSONObject params, SysUser user){
        Long showDate = params.getLong("showDate");
        DateTime dateTime = new DateTime(showDate);
        Calendar calendar = dateTime.toCalendar();
        calendar.add(Calendar.DATE, -1);
        Date yesterdayShowDate = calendar.getTime();

        List<MediaNewList> mediaNewLists = baseMapper.selectList(
                Wrappers.<MediaNewList>lambdaQuery()
                        .eq(MediaNewList::getShowDate, yesterdayShowDate.getTime())
                        .eq(MediaNewList::getIsDel, CommonEnum.DelEnum.UNDEL.val()));
        long currentTime = System.currentTimeMillis();
        mediaNewLists.forEach(mediaNewList -> {
            mediaNewList.setId(null);
            mediaNewList.setCreateTime(currentTime);
            mediaNewList.setCreateUser(user.getUserName());
            mediaNewList.setShowDate(showDate);
            mediaNewList.setShowBeginTime(addDayOne(mediaNewList.getShowBeginTime()));
            mediaNewList.setShowEndTime(addDayOne(mediaNewList.getShowEndTime()));
            if(currentTime > mediaNewList.getShowEndTime()){
                mediaNewList.setStatus(MediaEnum.StatusEnum.REPLAY.val());
            }else{
                mediaNewList.setStatus(MediaEnum.StatusEnum.WAIT.val());
            }
            mediaNewList.setReplayFileId(null);
            mediaNewList.setReplayUrl(null);
            mediaNewList.setTaskId(null);
            mediaNewList.setRequestId(null);
            mediaNewList.setListenInNum(0);

            int insert = baseMapper.insert(mediaNewList);
            if(insert > 0){
                if(mediaNewList.getShowEndTime() > currentTime && mediaNewList.getShowBeginTime() > currentTime){
                    mediaNewListAsyncService.createLiveRecord(mediaNewList.getId(),
                            DateUtil.format(new Date(mediaNewList.getShowBeginTime()),DatePattern.NORM_DATETIME_PATTERN),
                            DateUtil.format(new Date(mediaNewList.getShowEndTime()),DatePattern.NORM_DATETIME_PATTERN));
                }
            }
        });
        return showDate;
    }

    private Long addDayOne(long time){
        DateTime dateTime = new DateTime(time);
        Calendar calendar = dateTime.toCalendar();
        calendar.add(Calendar.DATE, 1);
        Date date = calendar.getTime();
        return date.getTime();
    }
}
